// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.onboarding

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import kotlinx.coroutines.runBlocking
import xyz.apiote.bimba.czwek.R
import xyz.apiote.bimba.czwek.account.AccountActivity
import xyz.apiote.bimba.czwek.dashboard.MainActivity
import xyz.apiote.bimba.czwek.data.sources.Server
import xyz.apiote.bimba.czwek.repo.migrateDB
import xyz.apiote.bimba.czwek.settings.DownloadCitiesWorker
import xyz.apiote.bimba.czwek.settings.feeds.migrateFeedInfoCache
import xyz.apiote.bimba.czwek.settings.feeds.migrateFeedsSettings
import xyz.apiote.bimba.czwek.settings.feeds.migrateGeocodingSettings

class FirstRunActivity : AppCompatActivity() {
	override fun onCreate(savedInstanceState: Bundle?) {
		installSplashScreen()
		super.onCreate(savedInstanceState)

		runBlocking {
			Server.get(this@FirstRunActivity).getTraffic(this@FirstRunActivity)
			migrateFeedsSettings(this@FirstRunActivity)
			migrateDB(this@FirstRunActivity)
			migrateGeocodingSettings(this@FirstRunActivity)
			migrateFeedInfoCache(this@FirstRunActivity)
		}
		createNotificationChannels()

		if (DownloadCitiesWorker.shouldUpdate(this)) {
			WorkManager.getInstance(this)
				.enqueue(OneTimeWorkRequest.from(DownloadCitiesWorker::class.java))
		}

		val intent = if (getFirstRun(this)) {
			Intent(this, AccountActivity::class.java)
		} else {
			Intent(this, MainActivity::class.java)
		}
		startActivity(intent)
		finish()
	}

	private fun createNotificationChannels() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			val name = getString(R.string.cities_channel_name)
			val descriptionText = getString(R.string.cities_channel_description)
			val importance = NotificationManager.IMPORTANCE_LOW
			val channel = NotificationChannel(DownloadCitiesWorker.NOTIFICATION_CHANNEL, name, importance).apply {
				description = descriptionText
			}
			val notificationManager: NotificationManager =
				getSystemService(NOTIFICATION_SERVICE) as NotificationManager
			notificationManager.createNotificationChannel(channel)
		}
	}

	companion object {
		private const val PREFERENCES_NAME = "shp"
		private const val FIRST_RUN_KEY = "firstRun"

		fun setFirstRunDone(context: Context) {
			context.getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE).edit {
				putBoolean(FIRST_RUN_KEY, false)
			}
		}

		fun getFirstRun(context: Context): Boolean {
			return context.getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE).getBoolean(FIRST_RUN_KEY, true)
		}
	}
}